import Taro, { Component } from '@tarojs/taro'
import { View, Picker } from '@tarojs/components'
import Next from '../../../static/user/icon_next.png';
import NavigationBar from '../../../components/navigationBar/index';

import * as echarts from '../../../components/ec-canvas/echarts'

import './index.scss'
import { userPerformance } from '../../../services/user';

let option = {
  xAxis: {
    type: 'category',
    splitLine: {
      show: false,
    },
    axisTick: { show: false },
    axisLabel: {
      textStyle: {
        color: '#A9A9A9',
      },
    },
    data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
  },
  grid: {
    x: 40,
    y: 20,
    x2: 10,
    y2: 40,
    show: true,
    // width: {totalWidth} - x - x2,
    // height: {totalHeight} - y - y2,
    backgroundColor: '#323232',
    borderWidth: 0,
    borderColor: '#ccc'
  },
  yAxis: {
    splitLine: {
      show: false,
    },
    axisTick: { show: false },
    axisLabel: {
      textStyle: {
        color: '#A9A9A9',
      },
    },
    type: 'value'
  },
  series: [{
    name: '成交',
    type: 'line',
    smooth: true,
    data: [10, 12, 21, 54, 260, 830, 710, 10, 10, 10, 10],
    lineStyle: {
      color: '#1F5FF8',
    },
    itemStyle: {
      color: '#1F5FF8',
    },
    markPoint: {
      symbolSize: 8,
      symbol: 'circle',
      label: {
        show: false,
      },
      data: [
        { type: 'max', name: '最大值' },
      ]
    },
  },
  {
    name: '预购',
    type: 'line',
    smooth: true,
    data: [30, 182, 434, 791, 390, 30, 10],
    lineStyle: {
      color: '#F8A01F',
    },
    itemStyle: {
      color: '#F8A01F',
    },
    markPoint: {
      symbolSize: 8,
      symbol: 'circle',
      label: {
        show: false,
      },
      data: [
        { type: 'max', name: '最大值' },
      ]
    },
  },
  {
    name: '意向',
    type: 'line',
    smooth: true,
    data: [1320, 1132, 601, 234, 120, 90, 20],
    lineStyle: {
      color: '#F81F4A',
    },
    itemStyle: {
      color: '#F81F4A',
    },
    markPoint: {
      symbolSize: 8,
      symbol: 'circle',
      label: {
        show: false,
      },
      data: [
        { type: 'max', name: '最大值' },
      ]
    },
  }]
};

function setChartData(chart, data) {
  chart.setOption(option);
}


export default class Echarts extends Component {

  config = {
    navigationBarTextStyle: 'white',
    navigationBarTitleText: '我的记录',
    navigationBarBackgroundColor: '#262626',
    backgroundTextStyle: 'light',
    usingComponents: {
      'ec-canvas': '../../../components/ec-canvas/ec-canvas' // 书写第三方组件的相对路径
    }
  }

  Chart = Taro.createRef();

  componentWillMount() {
    this.setState({
      agencyId: this.$router.params.id
    }, () => {
      userPerformance({
        start_time: parseInt(new Date(this.state.selectedTime.start).getTime() / 1000, 10),
        end_time: parseInt(new Date(this.state.selectedTime.end).getTime() / 1000, 10),
        id: this.state.agencyId
      }).then(data => {
        console.log(this.state.selectedTime)
        // let { start, end } = {...this.state.selectedTime}
        option.xAxis.data = ['1', '31']
        option.series[0].data = [...data.card]
        option.series[1].data = [...data.fish]
        option.series[2].data = [...data.all]
        this.refresh(option)
      })
    })
  }

  componentDidMount() {}

  state = {
    ec: {
      lazyLoad: true
    },
    navigationBarHeight: Taro.getStorageSync('navigationBarHeight'),
    selectedTime: {
      start: `${new Date().getFullYear()}-${this.monthFullZero(new Date().getMonth())}`,
      end: `${new Date().getMonth() + 1 > 11 ? new Date().getFullYear() + 1 : new Date().getFullYear()}-${new Date().getMonth() + 1 > 11 ? '01' : this.monthFullZero(new Date().getMonth() + 1)}`,
    },
    typeRange: ['月份', '季度', '年'],
    typeRangeIndex: 0,
    agencyId: null,
  };

  monthFullZero(month) {
    return month > 9 ? month : '0' + month
  }

  refresh = (data) => {
    this.Chart.current.init((canvas, width, height) => {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      setChartData(chart, data);
      return chart;
    });
  }

  handleDate = (e) => {
    // 0 strat 1 end
    console.log('handleDate', e);
    let data = []
    let time = {...this.state.selectedTime};
    let year = parseInt(e.detail.value.split('-')[0], 10)
    let month = parseInt(e.detail.value.split('-')[1], 10)
    let index = this.state.typeRangeIndex
    index = parseInt(index, 10)
    console.log(year, month)
    if (index === 0) {
      time.start = e.detail.value
      if (month > 11) {
        time.end = `${year + 1}-01`
      } else {
        time.end = `${year}-${this.monthFullZero(month + 1)}`
      }
      data = ['月初', '月末']
    } else if (index === 1) {
      time.start = e.detail.value
      if (month > 9) {
        time.end = `${year + 1}-${this.monthFullZero(month + 3 - 12)}`
      } else {
        time.end = `${year}-${this.monthFullZero(month + 3)}`
      }
      let temp = parseInt(time.start.split('-')[1], 10)
      if (temp < 10) {
        data = [temp > 10 ? temp : '0' + temp, temp + 1, temp + 2, temp + 3]
      } else if (temp === 10) {
        data = [10, 11, 12, '01']
      } else if (temp === 11) {
        data = [11, 12, '01', '02']
      } else if (temp === 12) {
        data = ['12', '01', '02', '03']
      }
    } else if (index === 2) {
      time.start = e.detail.value
      time.end = `${year + 1}-${month}`
      data = [time.start, time.end]
    }
    this.setState({
      selectedTime: time
    }, () => {
        userPerformance({
          start_time: parseInt(new Date(this.state.selectedTime.start).getTime() / 1000, 10),
          end_time: parseInt(new Date(this.state.selectedTime.end).getTime() / 1000, 10),
          id: this.state.agencyId
        }).then(res => {
          // 绘制数据
          console.log(this.state.selectedTime)
          option.xAxis.data = data
          if (this.state.typeRangeIndex === 2) {
            option.series[0].data = [res.card[0], res.card[res.card.length - 1]]
            option.series[1].data = [res.fish[0], res.fish[res.fish.length - 1]]
            option.series[2].data = [res.all[0], res.all[res.all.length - 1]]
          } else {
            option.series[0].data = [...res.card]
            option.series[1].data = [...res.fish]
            option.series[2].data = [...res.all]
          }
          this.refresh(option)
        })
    })
  }

  handleType(e) {
    console.log(e)
    let time = {}
    let data = []  // echarts横坐标显示
    let index = parseInt(e.detail.value, 10)
    if (index === 0) {
      // 月份
      time = {
        start: `${new Date().getFullYear()}-${this.monthFullZero(new Date().getMonth())}`,
        end: `${new Date().getFullYear()}-${this.monthFullZero(new Date().getMonth() + 1)}`,
      }
      data = ['1', '31']
    } else if (index === 1) {
      // 季度
      time = {
        start: `${new Date().getFullYear()}-${this.monthFullZero(new Date().getMonth() - 2 > 0 ? new Date().getMonth() - 2 : 1)}`,
        end: `${new Date().getFullYear()}-${this.monthFullZero(new Date().getMonth() + 1 > 12 ? 12 : new Date().getMonth() + 1)}`,
      }
      let temp = parseInt(time.start.split('-')[1], 10)
      if (temp < 10) {
        data = [this.monthFullZero(temp), this.monthFullZero(temp + 1), this.monthFullZero(temp + 2), this.monthFullZero(temp + 3)]
      } else if (temp === 10) {
        data = [10, 11, 12, '01']
      } else if (temp === 11) {
        data = [11, 12, '01', '02']
      } else if (temp === 12) {
        data = [12, '01', '02', '03']
      }
    } else if (index === 2) {
      // 年份
      time = {
        start: `${new Date().getFullYear() - 1}-${this.monthFullZero(new Date().getMonth() + 1)}`,
        end: `${new Date().getFullYear()}-${this.monthFullZero(new Date().getMonth() + 1)}`,
      }
      data = [time.start, time.end]
    }
    this.setState({
      typeRangeIndex: index,
      selectedTime: time
    }, () => {
        userPerformance({
          start_time: parseInt(new Date(this.state.selectedTime.start).getTime() / 1000, 10),
          end_time: parseInt(new Date(this.state.selectedTime.end).getTime() / 1000, 10),
          id: this.state.agencyId
        }).then(res => {
          // 绘制数据
          console.log(this.state.selectedTime)
          option.xAxis.data = data
          if (index === 2) {
            option.series[0].data = [res.card[0], res.card[res.card.length - 1]]
            option.series[1].data = [res.fish[0], res.fish[res.fish.length -1]]
            option.series[2].data = [res.all[0], res.all[res.all.length -1]]
          } else {
            option.series[0].data = [...res.card]
            option.series[1].data = [...res.fish]
            option.series[2].data = [...res.all]
          }
          this.refresh(option)
        })
    })
  }
  // refChart = node => (this.Chart = node);

  render () {
    const { selectedTime, typeRange, typeRangeIndex } = this.state;
    return (
      <View className='performance' style={`margin-top: ${navigationBarHeight}`}>
        <NavigationBar text={this.$router.params.nickname} />
        <View className="time">
          <Picker mode='date' fields="month" onChange={this.handleDate}>
            <View className='start'>
              {selectedTime.start}
            </View>
          </Picker>
          <View className="line">-</View>
          <Picker mode='date' fields="month" onChange={this.handleDate}>
            <View className='end'>
              {selectedTime.end}
            </View>
          </Picker>
          <Picker className="type-range" range={typeRange} value={typeRangeIndex} onChange={this.handleType}>
            <View className='type'>{typeRange[typeRangeIndex]}</View>
          </Picker>
        </View>
        <ec-canvas
          id="mychart-dom-area"
          ref={this.Chart}
          canvas-id="chart-example-line"
          ec={this.state.ec}
        />
        <View className="echart-tip">
          <View className="total tip">
            总销售额
          </View>
          <View className="fish tip">
            鱼的销售额
          </View>
          <View className="card tip">
            卡的销售额
          </View>
        </View>
      </View>
    )
  }
}

